/*
 * @Author: 徐建辰
 * @Date: 2022-02-12 15:51:38
 * @LastEditTime: 2022-02-17 11:24:02
 * @LastEditors: 徐建辰
 * @Description: 工具函数
 */
import {getItem} from './local'
import {USER} from './constant'

// 防抖函数时间id
let antiShakeId = 0
// 日期补0操作
const patchZero = num => {
  num = num < 10 ? '0' + num : num
  return num
}


// 获取title
export const getDocumentTitle = route => {
  if (route.meta && route.meta.title) {
    return route.meta.title
  }
  return 'hello'
}

// 判断是否有滚动条（兼容ie7、8）
export const hasScrollbar = () => document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight)

// 防抖函数
export const throttle = (fn, delay = 2000) => {
  let timeout = 0
  let lastRun = 0
  return function () {
    if (timeout) return
    console.log(this)
    const elapsed = Date.now() - lastRun
    const context = this
    const args = arguments
    const runCallback = function () {
      lastRun = Date.now()
      timeout = 0
      fn.apply(context, args)
    }
    if (elapsed >= delay) {
      runCallback()
    } else {
      timeout = window.setTimeout(runCallback, delay)
    }
  }
}

// 引用本地图片(这里路径不能用@/格式，否则vite打包会报错)
export const getImageUrl = (name, suffix = '.png') => new URL(`../assets/image/${name}`, import.meta.url).href

// 简单版防抖函数
export const antiShake = (callback, time = 2000) => {
  if (antiShakeId) clearTimeout(antiShakeId)
  antiShakeId = setTimeout(callback, time)
}

// 判断是否有用户信息
export const hasUser = () => {
  if (getItem(USER)) return true
  else return false
}

// 倒计时
export const countDown = time => {
  // 获取当前总的毫秒数
  const now = +new Date()
  // 后台返回的截止时间或者输入的总毫秒数
  const tTime = +new Date(time)
  // 求出剩余时间总毫秒数，并换算成秒
  const times = (tTime - now) / 1000
  // 计算天数
  let d = parseInt(times / 60 / 60 / 24)
  d = patchZero(d)
  // 计算小时
  let h = parseInt(times / 60 / 60 % 24)
  h = patchZero(h)
  // 计算分
  let m = parseInt(times / 60 % 60)
  m = patchZero(m)
  // 计算秒
  let s = parseInt(times % 60)
  s = patchZero(s)

  return `${d}天-${h}小时-${m}分-${s}秒`
}